﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using VAdvantage.Model;
using VAdvantage.Logging;
using VAdvantage.Utility;
using System.Text;
using System.ComponentModel;
using VAdvantage.DataBase;

namespace VAdvantage.Dialogs
{
    public partial class VLocatorDialog : ChildWindow
    {

        #region Declareartion

        private int _windowNo;
        private bool _change = false;
        private MLocatorLookup _mLocator;
        private int _M_Locator_ID;
        private bool _mandatory = false;
        private int _only_Warehouse_ID = 0;
        //
        private int _M_Warehouse_ID;
        private String _M_WarehouseValue;
        private String _separator;

        private bool _isOkPressed = false;
        private static VLogger log = VLogger.GetVLogger(typeof(VLocatorDialog).FullName);

        private string _title = "";

        #endregion

        public VLocatorDialog()
        {
            InitializeComponent();
            LayoutRoot.Background = new SolidColorBrush(GlobalVariable.WINDOW_BACK_COLOR);
        }

        public VLocatorDialog(String title, MLocatorLookup mLocator,
         int M_Locator_ID, bool mandatory, int only_Warehouse_ID, int windowNo)
            : this()
        {
            _title = title;
            _windowNo = windowNo;
            _mLocator = mLocator;
            _M_Locator_ID = M_Locator_ID;
            _mandatory = mandatory;
            _only_Warehouse_ID = only_Warehouse_ID;
            //
            //InitLocator();
            //this.BackColor = DataBase.GlobalVariable.WINDOW_BACK_COLOR;
        }

        private void OKButton_Click(object sender, RoutedEventArgs e)
        {
            ActionOk();
        }

        private void ActionOk()
        {



            if ((bool)chkCreateNew.IsChecked)
            {
                this.Cursor = Cursors.Wait;
                String mandatoryFields = "";
                //if (_M_Warehouse_ID == 0)
                //    mandatoryFields += lblWarehouse.Text + " - ";
                if (txtValue.Text.Length == 0)
                    mandatoryFields += lblValue.Content.ToString() + " - ";
                if (txtX.Text.Length == 0)
                    mandatoryFields += lblX.Content.ToString() + " - ";
                if (txtY.Text.Length == 0)
                    mandatoryFields += lblY.Content.ToString() + " - ";
                if (txtZ.Text.Length == 0)
                    mandatoryFields += lblZ.Content.ToString() + " - ";


                string lblWText = lblWarehouse.Content.ToString();

                string tValue = txtValue.Text, tX = txtX.Text, tY = txtY.Text, tZ = txtZ.Text;

                MLocator loc = null;

               // KeyNamePair pp = (KeyNamePair)cmbWarehouse.SelectedItem;
                System.Windows.Data.BindingSource source = cmbWarehouse.ItemsSource as System.Windows.Data.BindingSource;
                int warehouse_ID = Util.GetValueOfInt(((System.Data.BindableObject)source[cmbWarehouse.SelectedIndex]).GetValue("M_WAREHOUSE_ID"));

                BackgroundWorker bgw = new BackgroundWorker();

                bgw.DoWork += (sd, ed) =>
                    {
                       // if (pp != null)
                         //   GetWarehouseInfo(pp.GetKey());
                        if (warehouse_ID != 0)
                            GetWarehouseInfo(warehouse_ID);

                        if (_M_Warehouse_ID == 0)
                            mandatoryFields += lblWText + " - ";

                        if (mandatoryFields.Length != 0)
                        {
                            Classes.ShowMessage.Error("FillMandatory", true, mandatoryFields.Substring(0, mandatoryFields.Length - 3));
                            ed.Result = false;
                        }
                        else
                        {
                            loc = MLocator.Get(Envs.GetCtx(), _M_Warehouse_ID, tValue,
                                                        tX, tY, tZ);
                            _M_Locator_ID = loc.GetM_Locator_ID();
                            _mLocator.Refresh();

                            ed.Result = true;
                        }
                    };

                bgw.RunWorkerCompleted += (sc, ec) =>
                    {
                        if ((bool)ec.Result && loc != null)
                        {
                            //cmbLocator.Items.Add(loc.GetKeyNamePair());
                            //cmbLocator.SelectedItem = loc.GetKeyNamePair();
                            try
                            {
                                _mLocator._data.Add(loc.GetKeyNamePair());
                                cmbLocator.ItemsSource = _mLocator._data;
                                cmbLocator.SelectedItem = loc.GetKeyNamePair();
                            }
                            catch
                            {

                            }
                            _change = true;
                            _isOkPressed = true;
                            this.DialogResult = true;
                        }

                        this.Cursor = Cursors.Arrow;
                    };
                bgw.RunWorkerAsync();
            }
            else
            {
                _change = true;
                _isOkPressed = true;
                this.DialogResult = true;
            }
        }

        private void CancelButton_Click(object sender, RoutedEventArgs e)
        {
            _change = false;
            _isOkPressed = false;
            this.DialogResult = false;
        }

        private void ChildWindow_Loaded(object sender, RoutedEventArgs e)
        {
            this.Cursor = Cursors.Wait;

            System.Threading.ThreadPool.QueueUserWorkItem(delegate
            {
                InitLocator();
            });
        }

        string strLocator, strValue, strWarehouse, strWarehouseInfo, strX, strY, strZ, strCreateNew;
        public void InitLocator()
        {

            _title = Msg.Translate(Envs.GetCtx(), _title);

            strLocator = Msg.Translate(Envs.GetCtx(), "M_Locator_ID");
            strValue = Msg.Translate(Envs.GetCtx(), "Value");
            strWarehouse = Msg.Translate(Envs.GetCtx(), "M_Warehouse_ID");
            strWarehouseInfo = Msg.Translate(Envs.GetCtx(), "M_Warehouse_ID");
            strX = Msg.GetElement(Envs.GetCtx(), "X");
            strY = Msg.GetElement(Envs.GetCtx(), "Y");
            strZ = Msg.GetElement(Envs.GetCtx(), "Z");
            strCreateNew = Msg.GetMsg(Envs.GetCtx(), "CreateNew", true);

            //	Load Warehouse
            String sql = "SELECT M_Warehouse_ID, Name FROM M_Warehouse";
            if (_only_Warehouse_ID != 0)
                sql += " WHERE M_Warehouse_ID=" + _only_Warehouse_ID;
            String SQL = MRole.GetDefault().AddAccessSQL(
                sql, "M_Warehouse", MRole.SQL_NOTQUALIFIED, MRole.SQL_RO)
                + " ORDER BY 2";
            // System.Data.IDataReader dr = null;
            System.Data.DataSet ds = null;
            try
            {
                ds = DB.ExecuteDataset(SQL, null, null);
                //dr = DataBase.DB.ExecuteReader(SQL, null, null);
                //while (dr.Read())
                //{
                //    cmbWarehouse.Items.Add(new KeyNamePair(dr[0], dr.GetString(1)));
                //}
                //dr.Close();

            }
            catch (Exception e)
            {
                //if (dr != null)
                //{
                //    dr.Close();
                //}
                log.Severe(e.ToString());
                //Common.ErrorLog.FillErrorLog("VLocatorDialog.InitLocator", SQL, e.Message, Message.MessageType.ERROR);
            }
            //finally
            //{
            //    if (dr != null)
            //    {
            //        dr.Close();
            //    }
            //}

            _mLocator.Refresh();
            //	Load valid Locators
            _mLocator.FillComboBox(_mandatory, true, true, false);
            //log.fine(m_mLocator.toString());

            //System.Windows.Deployment.Current.Dispatcher.BeginInvoke(() => { Init2(); });
            System.Windows.Deployment.Current.Dispatcher.BeginInvoke(() => { Init2(ds); });
        }

        private void Init2(System.Data.DataSet dset)
        {
            this.Title = _title;
            this.lblLocator.Content = strLocator;
            this.lblValue.Content = strValue;
            this.lblWarehouse.Content = strWarehouse;
            this.lblWarehouseInfo.Content = strWarehouseInfo;
            this.lblX.Content = strX;
            this.lblY.Content = strY;
            this.lblZ.Content = strZ;
            this.chkCreateNew.Content = strCreateNew;

            cmbLocator.ItemsSource = _mLocator._data;
            if (cmbLocator.Items.Count >= 0)
            {
                cmbLocator.SelectedIndex = 0;
            }
            cmbLocator.DisplayMemberPath = "Name";
            SetSelectedLocator(_M_Locator_ID);
            //cmbLocator.SelectedValue = _M_Locator_ID;
            cmbLocator.SelectionChanged += new SelectionChangedEventHandler(cmbLocator_SelectedIndexChanged);

            DisplayLocator();
            //
            //fCreateNew.setSelected(false);
            if (_mLocator.IsOnly_Outgoing())
                chkCreateNew.Visibility = System.Windows.Visibility.Collapsed;
            else
            {
                chkCreateNew.Checked += new RoutedEventHandler(chkCreateNew_CheckedChanged);
                chkCreateNew.Unchecked += new RoutedEventHandler(chkCreateNew_CheckedChanged);
            }

            if (dset != null)
            {
                if (dset.Tables[0].Rows.Count > 0)
                {
                    System.Windows.Data.BindingSource source = new System.Windows.Data.BindingSource(dset.Tables[0].GetBindableData(new System.Data.Connector()));
                   
                    cmbWarehouse.ItemsSource = source;
                    cmbWarehouse.SelectedValuePath = "M_WAREHOUSE_ID";
                    cmbWarehouse.DisplayMemberPath = "NAME";
                    cmbWarehouse.SelectedIndex = 0;
                }
            }

            EnableNew();

            cmbWarehouse.SelectionChanged += new SelectionChangedEventHandler(cmbWarehouse_SelectedIndexChanged);

            txtX.KeyUp += new KeyEventHandler(txt_KeyUp);
            txtY.KeyUp += new KeyEventHandler(txt_KeyUp);
            txtZ.KeyUp += new KeyEventHandler(txt_KeyUp);
            this.Cursor = Cursors.Arrow;
        }

        //private void Init2()
        //{
        //    this.Title = _title;
        //    this.lblLocator.Content = strLocator;
        //    this.lblValue.Content = strValue;
        //    this.lblWarehouse.Content = strWarehouse;
        //    this.lblWarehouseInfo.Content =  strWarehouseInfo;
        //    this.lblX.Content = strX;
        //    this.lblY.Content = strY;
        //    this.lblZ.Content = strZ;
        //    this.chkCreateNew.Content = strCreateNew;

        //    cmbLocator.ItemsSource = _mLocator._data;
        //    cmbLocator.DisplayMemberPath = "Name";
        //    SetSelectedLocator(_M_Locator_ID);
        //    //cmbLocator.SelectedValue = _M_Locator_ID;
        //    cmbLocator.SelectionChanged += new SelectionChangedEventHandler(cmbLocator_SelectedIndexChanged);

        //    DisplayLocator();
        //    //
        //    //fCreateNew.setSelected(false);
        //    if (_mLocator.IsOnly_Outgoing())
        //        chkCreateNew.Visibility = System.Windows.Visibility.Collapsed;
        //    else
        //    {
        //        chkCreateNew.Checked += new RoutedEventHandler(chkCreateNew_CheckedChanged);
        //        chkCreateNew.Unchecked += new RoutedEventHandler(chkCreateNew_CheckedChanged);
        //    }

        //    EnableNew();

        //    cmbWarehouse.SelectionChanged += new SelectionChangedEventHandler(cmbWarehouse_SelectedIndexChanged);

        //    txtX.KeyUp += new KeyEventHandler(txt_KeyUp);
        //    txtY.KeyUp += new KeyEventHandler(txt_KeyUp);
        //    txtZ.KeyUp += new KeyEventHandler(txt_KeyUp);
        //    this.Cursor = Cursors.Arrow;
        //}

        void txt_KeyUp(object sender, KeyEventArgs e)
        {
            if ((bool)chkCreateNew.IsChecked)
                CreateValue();
        }
        /// <summary>
        ///Create Locator-Value
        /// </summary>
        private void CreateValue()
        {
            //	Get Warehouse Info
            //KeyNamePair pp = (KeyNamePair)cmbWarehouse.SelectedItem;
            //if (pp == null)
            //    return;

            System.Windows.Data.BindingSource source = cmbWarehouse.ItemsSource as System.Windows.Data.BindingSource;
            int warehouse_ID = Util.GetValueOfInt(((System.Data.BindableObject)source[cmbWarehouse.SelectedIndex]).GetValue("M_WAREHOUSE_ID"));
            if (warehouse_ID == 0)
                return;

            this.Cursor = Cursors.Wait;
            BackgroundWorker worker = new BackgroundWorker();

            worker.DoWork += (sd, ed) =>
            {
                //GetWarehouseInfo(pp.GetKey());
                GetWarehouseInfo(warehouse_ID);
            };
            //
            worker.RunWorkerCompleted += (sc, ec) =>
                {
                    StringBuilder buf = new StringBuilder(_M_WarehouseValue);
                    buf.Append(_separator).Append(txtX.Text);
                    buf.Append(_separator).Append(txtY.Text);
                    buf.Append(_separator).Append(txtZ.Text);
                    txtValue.Text = buf.ToString();

                    this.Cursor = Cursors.Arrow;
                };
            worker.RunWorkerAsync();
        }

        void cmbWarehouse_SelectedIndexChanged(object sender, SelectionChangedEventArgs e)
        {
            ///throw new NotImplementedException();
        }

        void chkCreateNew_CheckedChanged(object sender, EventArgs e)
        {
            EnableNew();
        }

        void cmbLocator_SelectedIndexChanged(object sender, SelectionChangedEventArgs e)
        {
            DisplayLocator();
        }

        private void SetSelectedLocator(int id)
        {
            int size = cmbLocator.Items.Count;
            for (int i = 0; i < size; i++)
            {
                KeyNamePair ppLoc = (KeyNamePair)cmbLocator.Items[i];
                if (ppLoc.GetKey() == id)
                {
                    cmbLocator.SelectedIndex = i;
                    break;
                }
            }
        }

        /// <summary>
        ///Display value of current locator
        /// </summary>
        private void DisplayLocator()
        {
            KeyNamePair pp = (KeyNamePair)cmbLocator.SelectedItem;
            if (pp == null || pp.GetKey() == 0)
                return;
            //
            _M_Locator_ID = pp.GetKey();
            MLocator loc = null;
            this.Cursor = Cursors.Wait;
            BackgroundWorker worker = new BackgroundWorker();

            worker.DoWork += (sd, ed) =>
                {
                    loc = MLocator.Get(Envs.GetContext(), _M_Locator_ID);
                    GetWarehouseInfo(loc.GetM_Warehouse_ID());
                };

            worker.RunWorkerCompleted += (sc, ec) =>
                {
                    //loc = MLocator.Get(Envs.GetContext(), _M_Locator_ID);
                    txtWarehouseInfo.Text = loc.GetWarehouseName();
                    txtX.Text = loc.GetX();
                    txtY.Text = loc.GetY();
                    txtZ.Text = loc.GetZ();
                    txtValue.Text = loc.GetValue();
                    //GetWarehouseInfo(loc.GetM_Warehouse_ID());
                    //	Set Warehouse
                    int size = cmbWarehouse.Items.Count;
                    System.Windows.Data.BindingSource source = cmbWarehouse.ItemsSource as System.Windows.Data.BindingSource;
                    
                    for (int i = 0; i < size; i++)
                    {
                        int wh_ID = Util.GetValueOfInt(((System.Data.BindableObject)source[i]).GetValue("M_WAREHOUSE_ID"));
                        //KeyNamePair ppWH = (KeyNamePair)cmbWarehouse.Items[i];
                        if (wh_ID == loc.GetM_Warehouse_ID())
                        {
                            cmbWarehouse.SelectedIndex = i;
                            continue;
                        }
                    }
                    worker = null;

                    this.Cursor = Cursors.Arrow;
                };
            worker.RunWorkerAsync();
        }

        /// <summary>
        /// Get Warehouse Info
        /// </summary>
        /// <param name="M_Warehouse_ID"></param>
        private void GetWarehouseInfo(int M_Warehouse_ID)
        {
            if (M_Warehouse_ID == _M_Warehouse_ID)
                return;
            MWarehouse wh = MWarehouse.Get(Envs.GetContext(), M_Warehouse_ID);
            _M_Warehouse_ID = wh.GetM_Warehouse_ID();
            _M_WarehouseValue = wh.GetValue();
            _separator = wh.GetSeparator();
        }

        private void EnableNew()
        {
            bool sel = chkCreateNew.IsChecked.Value;
            lblWarehouse.Visibility = sel ? System.Windows.Visibility.Visible : System.Windows.Visibility.Collapsed;
            cmbWarehouse.Visibility = sel ? System.Windows.Visibility.Visible : System.Windows.Visibility.Collapsed;
            lblWarehouseInfo.Visibility = !sel ? System.Windows.Visibility.Visible : System.Windows.Visibility.Collapsed;
            txtWarehouseInfo.Visibility = !sel ? System.Windows.Visibility.Visible : System.Windows.Visibility.Collapsed;
            txtX.IsReadOnly = !sel;
            txtY.IsReadOnly = !sel;
            txtZ.IsReadOnly = !sel;
            txtValue.IsReadOnly = !sel;
        }

        /// <summary>
        ///	Get Selected value
        /// </summary>
        /// <returns></returns>
        public Object GetValue()
        {
            KeyNamePair l = (KeyNamePair)cmbLocator.SelectedItem;
            if (l != null && l.GetKey() != 0)
                return l.GetKey();
            return null;
        }	//	getValue

        public string GetText()
        {
            KeyNamePair l = (KeyNamePair)cmbLocator.SelectedItem;
            if (l != null && l.GetName().Length != 0)
                return l.GetName();
            return "";
        }
    }
}

